<script setup lang="ts">
import { ref } from 'vue'

const article = ref('')

// SSE 服务器发送事件 (Server-Sent Events)
let source: EventSource
// 建立 SSE 连接
const connectSSE = () => {
  source = new EventSource('http://localhost:3000/chat_typing')
  // 通过事件获取
  source.addEventListener('message', (e) => {
    article.value += e.data
  })
}

// 关闭 SSE 连接
const closeSSE = () => {
  source.close()
}
</script>

<template>
  <h1>ChatGPT打字效果 - EventSource</h1>
  <button @click="connectSSE">建立 SSE 连接</button>
  <button @click="closeSSE">关闭 SSE 连接</button>
  <div class="box">
    {{ article }}
  </div>
</template>

<style scoped>
.box {
  width: 300px;
  height: 300px;
  background-color: pink;
  border: 1px solid #f00;
}
</style>
